package org.koyi.birrapp;

import org.koyi.database.FuncionesBaseDatos;
import org.koyi.entities.Bares;
import org.koyi.fragments.BarCervTapaVasoFragment;
import org.koyi.fragments.DetallesFragment;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class DetallesActivity extends FragmentActivity {
	
	private Bares selectedBar;
	
	private ViewPager pager;
	
    private FragmentStatePagerAdapter adapter; 
    
    private ScrollView scrollView = null;
    
    private GoogleMap map = null;
    
    private Fragment mapFragment = null;
    
    private ImageView imageTransparent = null;
    
    private MarkerOptions markerOptions = null;
    
    private TextView nombreBar;
    
    private Fragment detallesFragment = null;
    
    private View viewMarker = null;
    
    private TextView nombreBarMarker = null;
    
    private ToggleButton buttonFavorito = null;
    
    private FuncionesBaseDatos funcionesBaseDatos = new FuncionesBaseDatos();
    
    private String nombreBarFavorito = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detalles_activity);
		
		selectedBar = (Bares)getIntent().getSerializableExtra("selectedBar");
		
		buttonFavorito = (ToggleButton) findViewById(R.id.togglebutton);
		
		nombreBar = (TextView) findViewById(R.id.nombreBar);
	    nombreBar.setText(selectedBar.getNombre());
		
		scrollView = (ScrollView) findViewById(R.id.scrollView);
		
		if(isFavorito())
		{
			buttonFavorito.setChecked(true);
		}
		else
		{
			buttonFavorito.setChecked(false);
		}
		
		map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
		
		BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.bar_marker);
		markerOptions = new MarkerOptions()
							.position(new LatLng(selectedBar.getLatitud(), selectedBar.getLongitud()))
							.title(selectedBar.getNombre())
							.icon(bitmapDescriptor);
		map.addMarker(markerOptions);
		CameraPosition cameraPosition = new CameraPosition(
													new LatLng(selectedBar.getLatitud(), selectedBar.getLongitud()), 
													18, 60, 0);
		
	    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
	    
	    map.setInfoWindowAdapter(new InfoWindowAdapter() {
			
			@Override
			public View getInfoWindow(Marker marker) {
				viewMarker = DetallesActivity.this.getLayoutInflater().inflate(R.layout.info_window_no_button_layout, null);
				
				nombreBarMarker = (TextView) viewMarker.findViewById(R.id.nombreBarMarker);
				nombreBarMarker.setText(marker.getTitle());
				
				return viewMarker;
			}
			
			@Override
			public View getInfoContents(Marker arg0) {
				return null;
			}
		});
		
		imageTransparent = (ImageView) findViewById(R.id.transparent_image);
		imageTransparent.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int action = event.getAction();
		        switch (action) {
		           case MotionEvent.ACTION_DOWN:
		                scrollView.requestDisallowInterceptTouchEvent(true);
		                return false;

		           case MotionEvent.ACTION_UP:
		        	   scrollView.requestDisallowInterceptTouchEvent(false);
		                return true;

		           case MotionEvent.ACTION_MOVE:
		        	   scrollView.requestDisallowInterceptTouchEvent(true);
		                return false;

		           default: 
		                return true;
		        }   
			}
		});
		
		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
		detallesFragment = DetallesFragment.cargaSelectedBar(selectedBar);
		fragmentTransaction.replace(R.id.detalleFragment, detallesFragment);
		fragmentTransaction.commit();
		
		pager = (ViewPager) findViewById(R.id.viewPager);
         
        adapter=new FragmentStatePagerAdapter(
            getSupportFragmentManager()
            ){
    
            @Override
            public int getCount() {
               return selectedBar.getListaBirras().size();
            }
    
            @Override
            public Fragment getItem(int position) {
                return BarCervTapaVasoFragment.newInstance(selectedBar.getListaBirras().get(position));
            }
        };
        
        pager.setAdapter(adapter);
        
        pager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int newState) {
                if (newState == ViewPager.SCROLL_STATE_DRAGGING) {
                    // Prevent the ScrollView from intercepting this event now that the page is changing.
                    // When this drag ends, the ScrollView will start accepting touch events again.
                	scrollView.requestDisallowInterceptTouchEvent(true);
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            	scrollView.requestDisallowInterceptTouchEvent(true);
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            	scrollView.requestDisallowInterceptTouchEvent(true);
            }
        });
        
        buttonFavorito.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				SQLiteDatabase gruposDataBase = funcionesBaseDatos.conectaWritableBaseDeDatos(DetallesActivity.this);
				
				if(isChecked)
				{
					gruposDataBase.execSQL("INSERT INTO BARES (BAR_NOMBRE) " +
	                        			   "VALUES('" + selectedBar.getNombre() + "')") ;
	
					funcionesBaseDatos.cierraBaseDeDatos(gruposDataBase);
				}
				else if(!isChecked)
				{
					gruposDataBase.execSQL("DELETE FROM BARES WHERE " +
             			   				   "BAR_NOMBRE = '" + selectedBar.getNombre() + "'") ;

					funcionesBaseDatos.cierraBaseDeDatos(gruposDataBase);
				}
			}
		});
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
			detallesFragment = DetallesFragment.cargaSelectedBar(selectedBar);
			fragmentTransaction.remove(detallesFragment);
			fragmentTransaction.commit();
		}
	
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
	    int action = ev.getAction();
	    switch (action) {
	    case MotionEvent.ACTION_DOWN:
	        // Disallow ScrollView to intercept touch events.
	    	scrollView.requestDisallowInterceptTouchEvent(true);
	        break;

	    case MotionEvent.ACTION_UP:
	        // Allow ScrollView to intercept touch events.
	    	scrollView.requestDisallowInterceptTouchEvent(false);
	        break;
	    }

	    // Handle MapView's touch events.
	    super.onTouchEvent(ev);
	    return true;
	}


	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		
		outState.putSerializable("selectedBar", selectedBar);
	}
	
	private boolean isFavorito()
	{
		boolean favorito = false;
		
		SQLiteDatabase birrAppDataBase = funcionesBaseDatos.conectaWritableBaseDeDatos(DetallesActivity.this);
        
        String[] campos = new String[]{"_id", "BAR_NOMBRE"};
        String[] args = new String[]{selectedBar.getNombre()};
        
        if(birrAppDataBase != null){
                
            Cursor cursor = birrAppDataBase.query("BARES", campos, "BAR_NOMBRE=?", args, null, null, null);
            
            while(cursor.moveToNext())
            {
            	favorito = true;
            	nombreBarFavorito = cursor.getString(1);
            }
            
            funcionesBaseDatos.cierraBaseDeDatos(birrAppDataBase);
        }
        
		return favorito;
	}
}
